import { createContext, useContext } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
  loginUser,
  registerUser,
  fetchUserInfo as fetchUserInfoAction,
  updateUserInfo as updateUserInfoAction,
  updatePhoto as updatePhotoAction,
  updateIntroduce as updateIntroduceAction,
  logout as logoutAction,
  clearError as clearErrorAction,
  checkLoginStatus as checkLoginStatusAction,
  wechatLogin as wechatLoginAction,
  selectIsLoggedIn,
  selectUserInfo,
  selectToken,
  selectIsLoading,
  selectError
} from '../store/authSlice';

// 创建认证上下文 - 现在主要作为Redux的包装器
const AuthContext = createContext();

// 认证上下文提供者组件
export function AuthProvider({ children }) {
  return (
    <AuthContext.Provider value={{}}>
      {children}
    </AuthContext.Provider>
  );
}

// 自定义Hook，便于组件使用认证上下文（现在使用Redux）
export function useAuth() {
  const dispatch = useDispatch();
  
  // 从Redux获取状态
  const userInfo = useSelector(selectUserInfo);
  const token = useSelector(selectToken);
  const isLoggedIn = useSelector(selectIsLoggedIn);
  const isLoading = useSelector(selectIsLoading);
  const error = useSelector(selectError);

  // 检查登录状态
  const checkLoginStatus = () => {
    dispatch(checkLoginStatusAction());
  };

  // 登录方法
  const login = async (name, password) => {
    try {
      const resultAction = await dispatch(loginUser({ name, password }));
      if (loginUser.fulfilled.match(resultAction)) {
        // 登录成功后，等待一小段时间确保token已保存，然后获取用户详细信息
        try {
          // 添加短暂延迟确保token已保存到本地存储
          await new Promise(resolve => setTimeout(resolve, 100));
          await dispatch(fetchUserInfoAction());
        } catch (fetchError) {
          console.warn('获取用户详细信息失败:', fetchError);
          // 即使获取详细信息失败，登录仍然算成功
        }
        return { success: true };
      } else {
        return { 
          success: false, 
          message: resultAction.payload || '登录失败，请重试' 
        };
      }
    } catch (error) {
      return { success: false, message: error.message || '登录失败，请重试' };
    }
  };

  // 注册方法
  const register = async (name, password) => {
    try {
      const resultAction = await dispatch(registerUser({ name, password }));
      if (registerUser.fulfilled.match(resultAction)) {
        return { success: true };
      } else {
        // 处理从authSlice传递过来的错误信息
        const errorPayload = resultAction.payload;
        return { 
          success: false, 
          message: errorPayload?.message || '注册失败，请重试',
          status: errorPayload?.status,
          data: errorPayload?.data
        };
      }
    } catch (error) {
      return { 
        success: false, 
        message: error.message || '注册失败，请重试',
        status: error.status,
        data: error.data
      };
    }
  };

  // 获取用户详细信息方法
  const fetchUserInfo = async () => {
    try {
      const resultAction = await dispatch(fetchUserInfoAction());
      if (fetchUserInfoAction.fulfilled.match(resultAction)) {
        return { success: true, data: resultAction.payload };
      } else {
        return {
          success: false,
          message: resultAction.payload || '获取用户信息失败'
        };
      }
    } catch (error) {
      return { success: false, message: error.message || '获取用户信息失败' };
    }
  };

  // 更新用户头像方法
  const updatePhoto = async (photoPath) => {
    try {
      const resultAction = await dispatch(updatePhotoAction(photoPath));
      
      if (updatePhotoAction.fulfilled.match(resultAction)) {
        // 更新成功后，获取最新的用户信息
        await dispatch(fetchUserInfoAction());
        return { success: true };
      } else {
        return {
          success: false,
          message: resultAction.payload || '更新头像失败'
        };
      }
    } catch (error) {
      console.error('更新头像失败:', error);
      return { success: false, message: error.message || '更新头像失败' };
    }
  };

  // 更新用户简介方法
  const updateIntroduce = async (introduce) => {
    try {
      const resultAction = await dispatch(updateIntroduceAction(introduce));
      
      if (updateIntroduceAction.fulfilled.match(resultAction)) {
        // 更新成功后，获取最新的用户信息
        await dispatch(fetchUserInfoAction());
        return { success: true };
      } else {
        return {
          success: false,
          message: resultAction.payload || '更新简介失败'
        };
      }
    } catch (error) {
      console.error('更新简介失败:', error);
      return { success: false, message: error.message || '更新简介失败' };
    }
  };

  // 更新用户基本信息方法（兼容旧版本）
  const updateUserInfo = async (introduce, photoPath = null) => {
    try {
      // 确保introduce不为undefined或null
      const safeIntroduce = introduce || '';
      
      const resultAction = await dispatch(updateUserInfoAction({ introduce: safeIntroduce, photoPath }));
      
      if (updateUserInfoAction.fulfilled.match(resultAction)) {
        // 更新成功后，获取最新的用户信息
        await dispatch(fetchUserInfoAction());
        return { success: true };
      } else {
        return {
          success: false,
          message: resultAction.payload || '更新用户信息失败'
        };
      }
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return { success: false, message: error.message || '更新用户信息失败' };
    }
  };

  // 微信登录方法
  const wechatLogin = async (code) => {
    try {
      const resultAction = await dispatch(wechatLoginAction(code));
      if (wechatLoginAction.fulfilled.match(resultAction)) {
        return { 
          success: true, 
          isOldUser: resultAction.payload.isOldUser 
        };
      } else {
        return { 
          success: false, 
          message: resultAction.payload || '微信登录失败，请重试' 
        };
      }
    } catch (error) {
      return { success: false, message: error.message || '微信登录失败，请重试' };
    }
  };

  // 登出方法
  const logout = () => {
    dispatch(logoutAction());
  };

  // 清除错误
  const clearError = () => {
    dispatch(clearErrorAction());
  };

  return {
    userInfo,
    token,
    isLoggedIn,
    isLoading,
    error,
    login,
    register,
    fetchUserInfo,
    updateUserInfo,
    updatePhoto,
    updateIntroduce,
    wechatLogin,
    logout,
    checkLoginStatus,
    clearError
  };
}

export default AuthContext;